package com.felix.pattern.decoration;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Memoizer1
 *
 * @author xuejinhua
 * @date 2018/10/31 15:28
 */
public class Memoizer1<K, V> implements Computable<K, V> {

    private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<>();

    private Computable<K, V> computable;

    public Memoizer1(Computable<K, V> computable) {
        this.computable = computable;
    }

    @Override
    public V compute(K key) throws Exception {
        while (true) {
            Future<V> future = cache.get(key);
            if (future == null) {
                Callable<V> callable = () -> computable.compute(key);
                FutureTask<V> futureTask = new FutureTask<>(callable);
                // use putIfAbsent to avoid multi thread compute the same value
                future = cache.putIfAbsent(key, futureTask);
                if (future == null) {
                    future = futureTask;
                    futureTask.run();
                }
            }

            try {
                return future.get();
            } catch (InterruptedException e) {
                // remove cache and go into next loop to retry
                cache.remove(key, future);
            } catch (ExecutionException e) {
                // throw it and then end
                e.printStackTrace();
                throw e;
            }
        }
    }
}
